//
// SrvMetaResponse.cs
//
// Copyright (c) 2007 Lukas Lipka.
//

using System;
using System.Collections.Generic;
using System.Text;

using IcqSharp.Base;
using IcqSharp.Util;

namespace IcqSharp.Packets
{
    [SnacPacketType (0x0015, 0x0003)]
    class SrvMetaResponse : PacketHandler
    {
        public SrvMetaResponse (Session session, SnacPacket packet)
            : base (session, packet)
        {            
            DebugFu.WriteBytes(packet.Data);

            ushort data_type = EndianBitConverter.Little.ToUInt16(packet.Data, 10);
            Log.Debug("Received meta response - {0:X}!!!", data_type);

            switch (data_type)
            {
                case 0x0041:
                    OfflineMessages(packet.Data);
                    break;
            }
        }

        private void OfflineMessages(byte[] data)
        {
            string uin = EndianBitConverter.Little.ToUInt32(data, 14).ToString ();
            
            ushort year = EndianBitConverter.Little.ToUInt16(data, 18);            
            byte month = data[20];
            byte day = data[21];
            byte hour = data[22];
            byte minute = data[23];

            byte message_type = data[24];
            byte message_flags = data[25];

            ushort length = EndianBitConverter.Little.ToUInt16(data, 26);
            string text = Encoding.UTF8.GetString(data, 28, length - 1);

            DateTime date = new DateTime (year, month, day, hour, minute, 0);
            Contact c = Session.ContactList[uin];

            if (c == null)
                c = new Contact(uin);

            Log.Debug("Offline message ({0}) - {1}: {2}", c.Nickname, date, text);

            Message message = new Message(c, MessageType.Offline, date, text);
            Session.Messaging.OnOfflineMessageReceived(message);
        }
    }
}
